#include <REGX52.H>
#include "Delay.h"

/**
  * @brief 矩阵键盘读取按键键码。如果按下按键不放，程序会停留在此处，松手的一瞬间返回键码值。没有按键按下时返回0。
  * @param 无
  * @retval KeyNumber 按下的键码值
  */
unsigned char MatrixKey() {
	unsigned char KeyNumber = 0;
	
	// 先判断第一列中谁被按下（S1、S5、S9、S13）
	P1 = 0xFF;	// 将P1所有位都置高 1
	P1_3 = 0;	// 将P1_3置低 0
	if (P1_7 == 0) {Delay(20); while (P1_7 == 0); Delay(20); KeyNumber = 1;}
	if (P1_6 == 0) {Delay(20); while (P1_6 == 0); Delay(20); KeyNumber = 5;}
	if (P1_5 == 0) {Delay(20); while (P1_5 == 0); Delay(20); KeyNumber = 9;}
	if (P1_4 == 0) {Delay(20); while (P1_4 == 0); Delay(20); KeyNumber = 13;}
	
	// 判断第二列中谁被按下（S2、S6、S10、S14）
	P1 = 0xFF;	// 将P1所有位都置高 1
	P1_2 = 0;	// 将P1_2置低 0
	if (P1_7 == 0) {Delay(20); while (P1_7 == 0); Delay(20); KeyNumber = 2;}
	if (P1_6 == 0) {Delay(20); while (P1_6 == 0); Delay(20); KeyNumber = 6;}
	if (P1_5 == 0) {Delay(20); while (P1_5 == 0); Delay(20); KeyNumber = 10;}
	if (P1_4 == 0) {Delay(20); while (P1_4 == 0); Delay(20); KeyNumber = 14;}
	
	// 判断第三列中谁被按下（S3、S7、S11、S15）
	P1 = 0xFF;	// 将P1所有位都置高 1
	P1_1 = 0;	// 将P1_1置低 0
	if (P1_7 == 0) {Delay(20); while (P1_7 == 0); Delay(20); KeyNumber = 3;}
	if (P1_6 == 0) {Delay(20); while (P1_6 == 0); Delay(20); KeyNumber = 7;}
	if (P1_5 == 0) {Delay(20); while (P1_5 == 0); Delay(20); KeyNumber = 11;}
	if (P1_4 == 0) {Delay(20); while (P1_4 == 0); Delay(20); KeyNumber = 15;}
	
	// 判断第四列中谁被按下（S4、S8、S12、S16）
	P1 = 0xFF;	// 将P1所有位都置高 1
	P1_0 = 0;	// 将P1_0置低 0
	if (P1_7 == 0) {Delay(20); while (P1_7 == 0); Delay(20); KeyNumber = 2;}
	if (P1_6 == 0) {Delay(20); while (P1_6 == 0); Delay(20); KeyNumber = 6;}
	if (P1_5 == 0) {Delay(20); while (P1_5 == 0); Delay(20); KeyNumber = 10;}
	if (P1_4 == 0) {Delay(20); while (P1_4 == 0); Delay(20); KeyNumber = 14;}
	
	return KeyNumber;
}